const { Service } = require('egg')
const { tableToList } = require('../utils/tools')

module.exports = class GradeService extends Service {
  /**
   * * 成绩占比数据请求
   * @param {string} fromLink 占比详情请求地址
   * @return {object} *
   */
  async proportion(fromLink) {
    if (!fromLink) return []
    const Cookie = this.ctx.state.Cookie
    const apiUrl = encodeURI(fromLink)
    const res = await this.ctx.curl(apiUrl, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#dataList')
        return tableList
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return {}
  }

  /**
   * * 课程成绩查询
   * @param {String} term 学期
   * @return {Array} *
   */
  async table(term = 'all') {
    term = '2021-2022-1'
    const [xn, , xqRaw] = term ? term.split('-') : ['', '', '']
    if (xqRaw === '1') { term = ((xn - 2020) * 40 + 122).toString() }
    else { term = ((xn - 2020) * 40 + 142).toString() }
    const Cookie = this.ctx.state.Cookie
    // const CookieExp = this.ctx.state.CookieExp;
    // console.log('CookieExp', CookieExp);
    const apiUrl = `${this.ctx.state.baseUrl}/eams/teach/grade/course/person!search.action?semesterId=${term}&projectType=&_=1713580243275`
    // console.log('apiUrl', apiUrl);
    const res = await this.ctx.curl(apiUrl, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    // console.log('res', res.status)
    const header = ['课程名称', '类型', '学分', '成绩', '是否通过', '绩点', '课程性质'] // 列名称
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#grid1087012231')

        const columnNeed = [3, 5, 11, 12, 13, 4] // 需要提取的列序号

        const info = {}
        for (let i = 1; i < tableList.length; i++) {
          const terms = tableList[i][0]
          if ((terms in info) === false) { info[terms] = [] }
          const tem = []
          columnNeed.forEach((idx) => {
            if (idx === 11) {
              tem.push({
                score: tableList[i][idx],
                from: [{ type: '期末成绩', score: tableList[i][9] }, { type: '平时成绩', score: tableList[i][6] }],
              })
            }
            else if (idx !== 4) { tem.push(tableList[i][idx]) }
            else {
              tem.push(tableList[i][idx])
              tem.splice(1, 0, tableList[i][4].slice(2, 4))
            }
          })
          info[terms].push(tem)
        }

        return { table: info, header }
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return { table: {}, header }
  }
}
